package com.openness.spider.commons;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @author Rain
 * @version 2013-6-20 上午10:27:43
 */

public class MD5 {

	private static final MessageDigest DIGEST;

	static {
		try {
			DIGEST = MessageDigest.getInstance(Statics.DIGEST_ALGORITHM);
		} catch (NoSuchAlgorithmException e) {
			throw new ExceptionInInitializerError(e);
		}
	}

	private static String toHex(byte[] digest) {
		StringBuffer sb = new StringBuffer(digest.length * 2);

		for (int i = 0; i < digest.length; i++) {
			sb.append(Character.forDigit((digest[i] & 240) >> 4, 16));

			sb.append(Character.forDigit(digest[i] & 15, 16));
		}

		return sb.toString();
	}

	public static String md5(String str) {
		if (str == null) {
			return null;
		}

		DIGEST.update(str.getBytes(Statics.DEFAULT_ENCODE));

		byte[] digest = DIGEST.digest();

		return toHex(digest);
	}

	public static void main(String[] args) {
		String str1 = "my name is myr";

		String str2 = "我的名字是苗雨润";

		System.out.println(MD5.md5(str1));

		System.out.println(MD5.md5(str2));
	}

}
